package cn.edu.ujs.coor.service;

import cn.edu.ujs.coor.common.exception.CoorException;
import cn.edu.ujs.coor.model.Organization;
import cn.edu.ujs.coor.repository.organization.OrganizationMapper;
import cn.edu.ujs.coor.repository.organization.OrganizationRepository;
import cn.edu.ujs.coor.request.IdRequest;
import cn.edu.ujs.coor.request.organization.OrganizationAddRequest;
import cn.edu.ujs.coor.request.organization.OrganizationUpdateRequest;
import cn.edu.ujs.coor.response.OrganizationResponse;
import cn.edu.ujs.coor.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 组织Service
 *
 * @author 柳曾雄
 * @date 2018-08-31
 */
@Service
public class OrganizationService extends BaseService<Organization, OrganizationResponse> {

    @Autowired
    public void setMapper (OrganizationMapper mapper) {
        this.mapper = mapper;
    }

    @Autowired
    public void setRepository (OrganizationRepository repository) {
        this.repository = repository;
    }

    /**
     * 新增
     * @param request
     */
    public void add (OrganizationAddRequest request) {
        List<Organization> list = ((OrganizationRepository) repository).findByName(request.getName());
        if (list.size() > 0) {
            throw new CoorException("该组织已存在");
        }
        Organization organization = Organization.builder().build();
        BeanUtil.copyBeanIgnoreNull(organization, request);
        this.save(organization);
    }

    /**
     * 更新
     * @param request
     */
    public void update (OrganizationUpdateRequest request) {
        List<Organization> list = ((OrganizationRepository) repository).findByName(request.getName());
        if (list.size() > 0 && list.get(0).getId() == request.getId()) {
            throw new CoorException("该组织已存在");
        }
        Organization organization = this.findById(request.getId());
        BeanUtil.copyBeanIgnoreNull(organization, request);
        this.save(organization);
    }

    /**
     * 删除
     * @param request
     */
    public void delete (IdRequest request) {
        Organization organization = this.findById(request.getId());
        if (organization == null) {
            throw new CoorException("该组织不存在");
        }
        this.delete(organization);
    }
}
